const { apiRequest } = require('../../utils/dataokeSdkRequest');
const poolPromise = require('../../dataBase/index');
const db = require("../../dataBase/index")
const { unionId } = require("../../config/index")



const url = 'https://u.jd.com/mbCmKZD'

/** 调用`京东链接解析`接口获取商品的ID */
const parseGoodUrl = async (url) => {
    /**
     * {"status":200,"data":{"cache":false,"code":0,"data":{"skuId":"2922989","itemUrl":"https://item.m.jd.com/product/2922989.html","hasCoupon":"0","couponLink":""},"msg":"成功","requestId":"8c8c1879ee12a25cea1f5dfca6113a09","time":1723023395810299},"msg":"请求成功"}
     */
    const res = await apiRequest('https://openapi.dataoke.com/api/dels/jd/kit/parseUrl', {
        method: "GET",
        form: { url, version: "v1.0.0" }
    })
    console.log('打印***res parse', res)
    if (res && res.code === 0 && res.data) {
        return res.data
    }
    return false
}

/** 2、调用`京东联盟搜索`接口获取商品详细信息 */
const getGoodDetail = async (url) => {
    const { skuId, itemUrl } = await parseGoodUrl(url)
    const goodUrl = await replaceGoodUrl(itemUrl)
    if (!skuId) return
    const res = await apiRequest('https://openapi.dataoke.com/api/dels/jd/goods/search', {
        method: "GET",
        form: { skuIds: skuId, version: "v1.0.0" }
    })
    console.log('打印***res detail', res)
    if (res.code === 0 && res.data && res.data.list && res.data.list.length) {
        const {
            skuName,// 商品名称
            lowestCouponPrice,//券后价（有无券都返回此字段，价格排序以此字段排序）
            couponCommission,//券后佣金，（促销价-优惠券面额）佣金比例
            lowestPrice,//促销价
            price,//商品价格
        } = res.data.list[0]

        return {
            goodName: skuName,
            afterPrice: lowestCouponPrice,
            returnMoney: couponCommission,
            coupon: Math.ceil(lowestPrice - lowestCouponPrice),
            goodUrl: goodUrl,
        }
    }
}

/** 3、调用`京东商品转链`接口将商品转换成自己的推广链接 materialId是商品url */
const replaceGoodUrl = async (materialId, wechatId, accountName) => {
    // let sql = `select * from user where wechat_uid='${wechatId}' and accountName='${accountName}'`
    // let sqlRes = await db.execute(sql)
    // console.log('打印***sqlRes', sqlRes)
    // let user_id = 0
    // if (sqlRes.length > 0) {
    //     user_id = sqlRes[0].user_id
    // }

    const res = await apiRequest('https://openapi.dataoke.com/api/dels/jd/kit/promotion-union-convert', {
        method: "GET",
        form: { unionId, materialId, version: "v1.0.0" }
    })
    console.log('打印***res====', res)

    if (res.code === 0 && res.data) {
        return res.data.shortUrl
    }
}


module.exports = {
    getGoodDetail
}